package com.lic.system.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.lic.system.exception.RRException;
import com.lic.system.pojo.User;
import com.lic.system.pojo.UserToken;
import com.lic.system.service.UserService;
import com.lic.system.service.UserTokenService;
import com.lic.system.threadLocal.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Hewb
 * @ClassName: UserInterceptor
 * @Description: TODO
 * @date: 2020/7/13 10:15
 * @since JDK 1.8
 */

@Slf4j
public class UserInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    UserTokenService userTokenService;

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new RRException("未获取登录信息", HttpStatus.UNAUTHORIZED.value());
        }
        UserToken userToken = userTokenService.queryByToken(token);
        if (userToken==null) {
            throw new RRException("登录失效,请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
        boolean before = userToken.getExpireTime().before(new Date());
        if (before) {
            throw new RRException("登录失效,请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
        User user = userService.queryUser(userToken.getUserId());

        UserThreadLocal.set(user);

        userTokenService.updateById(userToken);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //销毁线程
        UserThreadLocal.remove();
    }

}
